/**
 *    Copyright 2010 Merrick Zhang ( anphorea@gmail.com )
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */
package anpho.proxyvalidator.provider;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Set;

import anpho.proxyvalidator.config.AppContext;

/**
 * @author Merrick
 * 
 */
public abstract class AProxyProvider {

	public abstract Set<Proxy> getProxies();

	private static int READ_TIMEOUT = AppContext.getInt("READ_TIMEOUT");

	private static int CONN_TIMEOUT = AppContext.getInt("CONN_TIMEOUT");

	static {
		if (READ_TIMEOUT == 0) {
			READ_TIMEOUT = 1000 * 5;
		}
		if (CONN_TIMEOUT == 0) {
			CONN_TIMEOUT = 1000 * 5;
		}
	}

	/**
	 * Get remote file and return the file content as a String.
	 * 
	 * @param url
	 *            the URL
	 * @return the content
	 * @throws IOException
	 *             oops,error occurs.
	 */
	public static String getFileAsString(String url) throws IOException {
		StringBuffer sb = new StringBuffer();
		URL u = new URL(url);
		URLConnection c = u.openConnection();
		c.setReadTimeout(READ_TIMEOUT);
		c.setConnectTimeout(CONN_TIMEOUT);
		BufferedReader br = null;
		try {
			c.connect();
			br = new BufferedReader(new InputStreamReader(c.getInputStream()));
			while (br.ready()) {
				sb.append(br.readLine());
			}
			br.close();
		} catch (IOException e) {
			throw e;
		} finally {
			if (null != br) {
				br.close();
			}
		}
		return sb.toString();
	}

	/**
	 * @param cONNTIMEOUT
	 *            the cONN_TIMEOUT to set
	 */
	public static void setCONN_TIMEOUT(int cONNTIMEOUT) {
		CONN_TIMEOUT = cONNTIMEOUT;
	}

	/**
	 * @param rEADTIMEOUT
	 *            the rEAD_TIMEOUT to set
	 */
	public static void setREAD_TIMEOUT(int rEADTIMEOUT) {
		READ_TIMEOUT = rEADTIMEOUT;
	}
}
